﻿using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.CompilerServices;
public class PdfMerge
{
    /// <summary>
    /// // http://www.dotnetspider.com/resources/36210-Merge-PDF-File-using-itextsharp-library.aspx
    /// Here i develop a class for merge pdf file in to C#.net using free source dll itextsharp.
    /// Requirement: download iTextSharp.dll from below link
    /// http://sourceforge.net/projects/itextsharp/
    /// U should have .net framework on your machine.
    /// Just copy paste this class in your project and use it by creating object of that class and passing sourceFiles array 
    /// which contain all pdf file name which u want to merge and one destinationFile which u need to resulting final pdf file.
    /// Only u need to add reference of that dll in your project and this class is working very well.
    /// </summary>
    /// <param name="destinationFile"></param>
    /// <param name="sourceFiles"></param>
    /// 
    PdfWriter writer;
    PdfContentByte cb;

    [ZoneIdentityPermission(SecurityAction.Demand, Zone = SecurityZone.Internet)]
		
    public string MergeFiles(string destinationPath,System.Collections.Generic.List<string> sourceFiles)
    {
        string destinationFile = destinationPath + "\\combine.pdf";
        
        try
        {
            int f = 0;
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(sourceFiles[f]);
            // we retrieve the total number of pages
            int n = reader.NumberOfPages;
            //Console.WriteLine("There are " + n + " pages in the original file.");
            // step 1: creation of a document-object
            Document document = new Document(reader.GetPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            
            
            int ok = 0;
            while (ok != -1)
            {

                try
                {

                    writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
                   
                    ok = -1;
                    break;
                }
                catch (Exception exception)
                {
                    ok++;
                    destinationFile = destinationPath + "\\combine" + ok.ToString() + ".pdf";
                }
            }

            // step 3: we open the document
            document.Open();
            cb = writer.DirectContent;
            PdfImportedPage page;
            //Phrase phrase;
             BaseFont bf_helv = BaseFont.CreateFont(BaseFont.HELVETICA, "Cp1252", false);

            int y_line1 = 650;
            int y_line2 = y_line1 - 50;
            int y_line3 = y_line2 - 50;
            int rotation;
            // step 4: we add content
            while (f < sourceFiles.Count)
            {
                int i = 0;
                while (i < n)
                {

                    //if (i == 0)
                    //{
                    //    cb.BeginText();
                    //    cb.SetFontAndSize(bf_helv, 12);
                    //    String text = "Sample text for alignment";
                    //    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, y_line1, 0);
                    //    cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, y_line2, 0);
                    //    cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, y_line3, 0);
                    //    cb.EndText();
                    //}
                    //phrase = new Phrase("hihi");
                    //writer.Add(phrase);
                    //writer.Add(Chunk.NEWLINE);
                    //writer.NewPage();
                    i++;
                    document.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document.NewPage();
                    page = writer.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                    //Console.WriteLine("Processed page " + i);
                }

                f++;
               while (f < sourceFiles.Count)
                {
                    string filename =sourceFiles[f];
                    if (filename != null)
                    {
                        try
                        {
                            reader = new PdfReader(filename);
                        }
                        catch(Exception eee)
                        {
                            f++;
                        }
                            // we retrieve the total number of pages
                            n = reader.NumberOfPages;
                            //Console.WriteLine("There are " + n + " pages in the original file.");
                            break;
                        
                    }
                    else
                        f++;
                }

                
            }
            // step 5: we close the document
            document.Close();
        }
        catch (Exception e)
        {
            string strOb = e.Message;
        }
        return destinationFile;
    }

    public int CountPageNo(string strFileName)
    {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(strFileName);
        // we retrieve the total number of pages
        return reader.NumberOfPages;
    }
}